package net.sansi.v3correctserver.service.camera.cameras;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.annotation.JsonIgnore;
import net.sansi.v3correctserver.exception.ServiceException;
import net.sansi.v3correctserver.service.camera.Camera;

import java.io.IOException;
import java.io.InputStream;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Fang
 * create time : 2024/11/25
 * IDE : IntelliJ IDEA
 */

public abstract class CanonExeCameraBase extends Camera {


    static Map<Integer, CanonTvItem> tvMap = new HashMap<>();

    /**
     * 获取 快门选项
     *
     * @param ms 毫秒数
     * @return 快门时间
     */
    @JsonIgnore
    public CanonTvItem getTvItem(int ms) {
        if (tvMap.containsKey(ms)) return tvMap.get(ms);
        List<Camera.CanonTvItem> tvs = getTvs();
        tvs.sort(Comparator.comparingInt(CanonTvItem::getMs));
        int left = 0, right = tvs.size() - 1, pos = 0;
        while (left <= right) {
            int mid = (left + right) >> 1;
            if (tvs.get(mid).getMs() == ms) {
                pos = mid;
                break;
            }
            if (Math.abs(tvs.get(mid).getMs() - ms) < Math.abs(tvs.get(pos).getMs() - ms)) {
                pos = mid;
            }
            if (tvs.get(mid).getMs() > ms) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        CanonTvItem item = tvs.get(pos);
        tvMap.put(ms, item);
        return item;
    }

    List<Camera.CanonTvItem> canonTvItems = null;

    @JsonIgnore
    public List<Camera.CanonTvItem> getTvs() {
        if (canonTvItems != null) return canonTvItems;
        ClassLoader classLoader = FileUtil.class.getClassLoader();
        try (InputStream resource = classLoader.getResourceAsStream("camera/canon/tvs.json")) {
            String json = new String(resource.readAllBytes());
            List<Camera.CanonTvItem> items = JSONUtil.toList(json, CanonTvItem.class);
            canonTvItems = items;
            return items;
        } catch (IOException e) {
            throw new ServiceException("tvs文件不存在");
        }
    }

}
